package com.hzw.saas.common.security.config;

import com.hzw.saas.common.security.token.MyDefaultAccessTokenConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 资源服务器，请重新注入以下类，
 * @author sonam
 * @sine 2021/11/2 5:55 下午
 */
@Configuration
@RequiredArgsConstructor
public class JwtConfig {
    public static final String SIGNING_KEY = "hzw_saas_r2";
//    private final UserDetailsService userDetailsService;

    @Bean
    @ConditionalOnMissingBean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    @ConditionalOnMissingBean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(SIGNING_KEY);
        converter.setAccessTokenConverter(accessTokenConverter());
        return converter;
    }

    // 解决SecurityUtils.getUser()错误的问题
    private AccessTokenConverter accessTokenConverter() {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        MyDefaultAccessTokenConverter userAuthenticationConverter = new MyDefaultAccessTokenConverter();
        // jwt token解析，使用userDetailsService select -> username 的额外信息，该项不需要
//        userAuthenticationConverter.setUserDetailsService(userDetailsService);
        accessTokenConverter.setUserTokenConverter(userAuthenticationConverter);
        return accessTokenConverter;
    }
}
